<template>
  <div>
    <!-- <div
      class="gva-search-box"
    >
      <el-form
        ref="elSearchFormRef"
        :inline="true"
        :model="searchInfo"
        class="demo-form-inline"
        :rules="searchRule"
        @keyup.enter="onSubmit"
      >

        <el-form-item>
          <el-input
            v-model="searchInfo.serverName"
            placeholder="请输入服务器名称"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchInfo.status"
            placeholder="选择状态"
            style="width: 150px"
            :clearable="true"
          >
            <el-option
              v-for="(item,key) in statusOptions"
              :key="key"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="search"
            @click="onSubmit"
          >查询</el-button>
          <el-button
            icon="refresh"
            @click="onReset"
          >重置</el-button>
        </el-form-item>
      </el-form>
    </div> -->
    <div
      v-if="selectPlatform == 2"
      class="gva-table-box"
    >
      <div class="gva-btn-list">
        <el-button
          type="primary"
          icon="plus"
          @click="openDialog"
        >新增</el-button>
        <!-- <el-popover
          v-model:visible="deleteVisible"
          :disabled="!multipleSelection.length"
          placement="top"
          width="160"
        >
          <p>确定要删除吗？</p>
          <div style="text-align: right; margin-top: 8px;">
            <el-button
              type="primary"
              link
              @click="deleteVisible = false"
            >取消</el-button>
            <el-button
              type="primary"
              @click="onDelete"
            >确定</el-button>
          </div> -->
        <!-- <template #reference>
            <el-button
              icon="delete"
              style="margin-left: 10px;"
              :disabled="!multipleSelection.length"
              @click="deleteVisible = true"
            >删除</el-button>
          </template> -->
        <!-- </el-popover> -->
      </div>
      <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        border
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column
          type="selection"
          width="55"
        /> -->

        <!-- <el-table-column
          align="left"
          label="日期"
          width="180"
        >
          <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column> -->
        <!-- <el-table-column
          align="left"
          label="GameHash"
          prop="gameHash"
        /> -->
        <!-- <el-table-column
          align="left"
          label="所属渠道"
          prop="platformId"
        >
          <template #default="scope">
            {{ filterDict(scope.row.platformId,platformOptions) }}
          </template>
        </el-table-column> -->
        <el-table-column
          align="left"
          label="版本名称"
          prop="name"
        />
        <el-table-column
          align="left"
          label="操作"
          fixed="right"
        >
          <template #default="scope">
            <!-- <el-button
              type="primary"
              link
              class="table-button"
              @click="getDetails(scope.row)"
            >
              <el-icon style="margin-right: 5px"><InfoFilled /></el-icon>
              查看详情
            </el-button> -->
            <el-button
              type="primary"
              link
              icon="edit"
              class="table-button"
              @click="updateQmVersionFunc(scope.row)"
            >变更</el-button>
            <el-button
              type="primary"
              link
              icon="delete"
              @click="deleteRow(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogFormVisible"
      :before-close="closeDialog"
      :title="type==='create'?'添加':'修改'"
      destroy-on-close
    >
      <el-scrollbar height="500px">
        <el-form
          ref="elFormRef"
          :model="formData"
          label-position="right"
          :rules="rule"
          label-width="100px"
        >
          <el-form-item
            label="版本名称:"
            prop="name"
          >
            <el-input
              v-model="formData.name"
              :clearable="true"
              placeholder="请输入版本名称"
            />
          </el-form-item>
          <el-form-item
            label="服务器:"
            prop="status"
          >
            <el-select
              v-model="formData.server_ids"
              placeholder="选择服务器"
              style="width:50%"
              :clearable="true"
              multiple
              @change="changeServer"
            >
              <el-option
                v-for="(item,key) in serverList"
                :key="key"
                :label="item.server_name"
                :value="item.id"
              >
                <span style="float: left">{{ item.server_name }}</span>
                <span
                  style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
        "
                >
                  {{ item.status === 1 ? '上线' : (item.status == 2 ? '维护' : '停服') }}
                </span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button
            type="primary"
            @click="enterDialog"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import {
  createQmVersion,
  deleteQmVersion,
  deleteQmVersionByIds,
  updateQmVersion,
  findQmVersion,
  getQmVersionList
} from '@/api/qmVersion'

import { getQmServerList } from '@/api/qmServer'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'

defineOptions({
  name: 'QmVersion'
})

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  name: '',
  server_ids: [],
  server_ids_str: '',
})

const selectPlatform = ref(1)
// 判断storage里platform是否存在 不存在直接不允许进入
const isPlatform = () => {
  const platform = localStorage.getItem('platform')
  if (platform == 0 || platform == '' || platform == null || platform == undefined) {
    ElMessage({
      type: 'error',
      message: '请先选择渠道'
    })
    selectPlatform.value = 1
    // setTimeout(() => {
    //   window.location.href = '/#/layout/dashboard'
    // }, 1000)
  } else {
    selectPlatform.value = 2
  }
}

isPlatform()

// 验证规则
const rule = reactive({
  name: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  server_ids: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  ],
})

const searchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
      if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
        callback(new Error('请填写结束日期'))
      } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
        callback(new Error('请填写开始日期'))
      } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
        callback(new Error('开始日期应当早于结束日期'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
})

const changeServer = (val) => {
  formData.value.server_ids_str = val.toString()
}

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  isPlatform()
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  isPlatform()
  const table = await getQmVersionList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
  }
}
getTableData()

// ============== 表格控制部分结束 ===============

const serverList = ref([])

// 获取需要的字典 可能为空 按需保留
const setOptions = async() => {
  const res = await getQmServerList({ page: 1, pageSize: 1000 })
  if (res.code === 0) {
    serverList.value = res.data.list
  }
}

// 获取需要的字典 可能为空 按需保留
setOptions()

// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteQmVersionFunc(row)
  })
}

// 批量删除控制标记
const deleteVisible = ref(false)

// 多选删除
const onDelete = async() => {
  const IDs = []
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据'
    })
    return
  }
  multipleSelection.value &&
        multipleSelection.value.map(item => {
          IDs.push(item.ID)
        })
  const res = await deleteQmVersionByIds({ IDs })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === IDs.length && page.value > 1) {
      page.value--
    }
    deleteVisible.value = false
    getTableData()
  }
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateQmVersionFunc = async(row) => {
  const res = await findQmVersion({ id: row.id })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data
    const stringArray = res.data.server_ids.split(',')
    const numberArray = stringArray.map(Number)
    formData.value.server_ids = numberArray
    dialogFormVisible.value = true
  }
}

// 删除行
const deleteQmVersionFunc = async(row) => {
  const res = await deleteQmVersion({ id: row.id })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 查看详情控制标记
const detailShow = ref(false)

// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}

// // 打开详情
// const getDetails = async(row) => {
//   // 打开弹窗
//   const res = await findQmVersion({ ID: row.ID })
//   if (res.code === 0) {
//     formData.value = res.data.reQmVersion
//     openDetailShow()
//   }
// }

// // 关闭详情弹窗
// const closeDetailShow = () => {
//   detailShow.value = false
//   formData.value = {
//     gameHash: '',
//     platformId: undefined,
//     serverName: '',
//     serverHash: '',
//     status: 0,
//   }
// }

// 打开弹窗
const openDialog = () => {
  isPlatform()
  type.value = 'create'
  dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    gameHash: '',
    platformId: undefined,
    serverName: '',
    serverHash: '',
    status: undefined,
  }
}
// 弹窗确定
const enterDialog = async() => {
  elFormRef.value?.validate(async(valid) => {
    if (!valid) return
    let res
    switch (type.value) {
      case 'create':
        res = await createQmVersion(formData.value)
        break
      case 'update':
        res = await updateQmVersion(formData.value)
        break
      default:
        res = await createQmVersion(formData.value)
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      getTableData()
    }
  })
}

</script>

<style>

</style>
